package com.servlet.login;

import com.dao.UserDao;
import com.dao.UserInfo;
import com.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author admin
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet.filter")
public class LoginServlet extends HttpServlet {
//    private  String encoding;


    private UserDao userDao = new UserInfo();

    @Override
    public void init() throws ServletException {
        //初始化字符编码
//        encoding = this.getServletContext().getInitParameter("encoding");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding(encoding);//设置请求编码格式
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        try {
            User user = userDao.login(userName,userPwd);
            //判断是否在数据库中查询到user
            if(user!=null){
                request.getSession().setAttribute("user",user);
                response.sendRedirect(request.getContextPath()+"/IndexInServlet.filter");
            }else{
                request.getRequestDispatcher("/error.jsp").forward(request,response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
